package com.xky.ui.module.salesManagement.select;

import com.xky.ui.module.salesManagement.select.SelectSalesOrder.QueryCriteria;
import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.SalesMassage;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售订单高级查询对话框
 */
public class AdvancedQueryDialog extends JDialog {

    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color SEARCH_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color RESET_BUTTON_COLOR = new Color(231, 76, 60);
    
    // 定义字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 20);
    private static final Font LABEL_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font FIELD_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
    
    // 状态代码到显示文本的映射
    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    static {
        STATUS_MAP.put("pending", "待处理");
        STATUS_MAP.put("confirmed", "已确认");
        STATUS_MAP.put("shipped", "已发货");
        STATUS_MAP.put("completed", "已完成");
        STATUS_MAP.put("cancelled", "已取消");
    }
    
    private static final Map<String, String> PAYMENT_STATUS_MAP = new HashMap<>();
    static {
        PAYMENT_STATUS_MAP.put("unpaid", "未支付");
        PAYMENT_STATUS_MAP.put("partial", "部分支付");
        PAYMENT_STATUS_MAP.put("paid", "已支付");
        PAYMENT_STATUS_MAP.put("refunded", "已退款");
    }
    
    // 反向映射（显示文本到状态代码）
    private static final Map<String, String> REVERSE_STATUS_MAP = new HashMap<>();
    static {
        for (Map.Entry<String, String> entry : STATUS_MAP.entrySet()) {
            REVERSE_STATUS_MAP.put(entry.getValue(), entry.getKey());
        }
    }
    
    private static final Map<String, String> REVERSE_PAYMENT_STATUS_MAP = new HashMap<>();
    static {
        for (Map.Entry<String, String> entry : PAYMENT_STATUS_MAP.entrySet()) {
            REVERSE_PAYMENT_STATUS_MAP.put(entry.getValue(), entry.getKey());
        }
    }
    
    // 日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 界面组件
    private JTextField orderIdField;
    private JTextField orderNumberField;
    private JTextField customerIdField;
    private JTextField startDateField;
    private JTextField endDateField;
    private JComboBox<String> orderStatusCombo;
    private JComboBox<String> paymentStatusCombo;
    private JTextField minAmountField;
    private JTextField maxAmountField;
    private JTextField warehouseIdField;
    private JTextField keywordField;
    
    private JTable resultTable;
    private DefaultTableModel tableModel;
    private JLabel resultCountLabel;
    
    private JTable mainTable; // 主界面表格引用
    private Runnable refreshAction; // 刷新主界面的操作
    
    /**
     * 创建高级查询对话框
     * @param mainTable 主界面表格
     * @param refreshAction 刷新主界面的操作
     */
    public AdvancedQueryDialog(JTable mainTable, Runnable refreshAction) {
        super(SwingUtilities.getWindowAncestor(mainTable) instanceof Frame ? 
              (Frame)SwingUtilities.getWindowAncestor(mainTable) : null, "销售订单高级查询", true);
        this.mainTable = mainTable;
        this.refreshAction = refreshAction;
        
        initComponents();
        setupLayout();
        setupListeners();
        
        // 设置对话框属性
        setSize(1000, 700);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
    /**
     * 初始化组件
     */
    private void initComponents() {
        // 初始化文本字段
        orderIdField = createTextField();
        orderNumberField = createTextField();
        customerIdField = createTextField();
        startDateField = createTextField();
        endDateField = createTextField();
        minAmountField = createTextField();
        maxAmountField = createTextField();
        warehouseIdField = createTextField();
        keywordField = createTextField();
        
        // 初始化下拉框
        orderStatusCombo = new JComboBox<>();
        orderStatusCombo.addItem("全部");
        for (String status : STATUS_MAP.values()) {
            orderStatusCombo.addItem(status);
        }
        orderStatusCombo.setFont(FIELD_FONT);
        orderStatusCombo.setBackground(Color.WHITE);
        
        paymentStatusCombo = new JComboBox<>();
        paymentStatusCombo.addItem("全部");
        for (String status : PAYMENT_STATUS_MAP.values()) {
            paymentStatusCombo.addItem(status);
        }
        paymentStatusCombo.setFont(FIELD_FONT);
        paymentStatusCombo.setBackground(Color.WHITE);
        
        // 初始化表格
        String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单时间", "订单状态", "支付状态", "订单总金额"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        resultTable = new JTable(tableModel);
        resultTable.setRowHeight(30);
        resultTable.setFont(FIELD_FONT);
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));
        resultTable.getTableHeader().setBackground(PRIMARY_COLOR);
        resultTable.getTableHeader().setForeground(Color.BLACK);
        resultTable.getTableHeader().setOpaque(true);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setShowGrid(true);
        resultTable.setGridColor(new Color(230, 230, 230));
        
        // 设置列宽
        resultTable.getColumnModel().getColumn(0).setPreferredWidth(70);
        resultTable.getColumnModel().getColumn(1).setPreferredWidth(120);
        resultTable.getColumnModel().getColumn(2).setPreferredWidth(70);
        resultTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        resultTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        resultTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        resultTable.getColumnModel().getColumn(6).setPreferredWidth(120);
        
        // 结果计数标签
        resultCountLabel = new JLabel("查询结果: 0 条记录");
        resultCountLabel.setFont(LABEL_FONT);
    }
    
    /**
     * 创建统一样式的文本字段
     * @return 文本字段
     */
    private JTextField createTextField() {
        JTextField textField = new JTextField();
        textField.setFont(FIELD_FONT);
        textField.setPreferredSize(new Dimension(150, 30));
        return textField;
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel titleLabel = new JLabel("销售订单高级查询");
        titleLabel.setFont(TITLE_FONT);
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        // 查询条件面板
        JPanel criteriaPanel = new JPanel(new GridBagLayout());
        criteriaPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(PRIMARY_COLOR),
                "查询条件",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                LABEL_FONT,
                PRIMARY_COLOR));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 10, 5, 10);
        
        // 第一行
        gbc.gridx = 0;
        gbc.gridy = 0;
        criteriaPanel.add(createLabelWithFont("订单ID:"), gbc);
        
        gbc.gridx = 1;
        criteriaPanel.add(orderIdField, gbc);
        
        gbc.gridx = 2;
        criteriaPanel.add(createLabelWithFont("订单编号:"), gbc);
        
        gbc.gridx = 3;
        criteriaPanel.add(orderNumberField, gbc);
        
        gbc.gridx = 4;
        criteriaPanel.add(createLabelWithFont("客户ID:"), gbc);
        
        gbc.gridx = 5;
        criteriaPanel.add(customerIdField, gbc);
        
        // 第二行
        gbc.gridx = 0;
        gbc.gridy = 1;
        criteriaPanel.add(createLabelWithFont("开始日期:"), gbc);
        
        gbc.gridx = 1;
        criteriaPanel.add(startDateField, gbc);
        
        gbc.gridx = 2;
        criteriaPanel.add(createLabelWithFont("结束日期:"), gbc);
        
        gbc.gridx = 3;
        criteriaPanel.add(endDateField, gbc);
        
        gbc.gridx = 4;
        criteriaPanel.add(createLabelWithFont("仓库ID:"), gbc);
        
        gbc.gridx = 5;
        criteriaPanel.add(warehouseIdField, gbc);
        
        // 第三行
        gbc.gridx = 0;
        gbc.gridy = 2;
        criteriaPanel.add(createLabelWithFont("订单状态:"), gbc);
        
        gbc.gridx = 1;
        criteriaPanel.add(orderStatusCombo, gbc);
        
        gbc.gridx = 2;
        criteriaPanel.add(createLabelWithFont("支付状态:"), gbc);
        
        gbc.gridx = 3;
        criteriaPanel.add(paymentStatusCombo, gbc);
        
        gbc.gridx = 4;
        criteriaPanel.add(createLabelWithFont("关键字:"), gbc);
        
        gbc.gridx = 5;
        criteriaPanel.add(keywordField, gbc);
        
        // 第四行
        gbc.gridx = 0;
        gbc.gridy = 3;
        criteriaPanel.add(createLabelWithFont("最小金额:"), gbc);
        
        gbc.gridx = 1;
        criteriaPanel.add(minAmountField, gbc);
        
        gbc.gridx = 2;
        criteriaPanel.add(createLabelWithFont("最大金额:"), gbc);
        
        gbc.gridx = 3;
        criteriaPanel.add(maxAmountField, gbc);
        
        // 日期格式提示
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 6;
        JLabel dateFormatLabel = new JLabel("日期格式: yyyy-MM-dd (例如: 2023-01-01)");
        dateFormatLabel.setFont(new Font("微软雅黑", Font.ITALIC, 12));
        dateFormatLabel.setForeground(Color.GRAY);
        criteriaPanel.add(dateFormatLabel, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        
        JButton searchButton = createStyledButton("查询", SEARCH_BUTTON_COLOR);
        JButton resetButton = createStyledButton("重置", RESET_BUTTON_COLOR);
        
        buttonPanel.add(searchButton);
        buttonPanel.add(resetButton);
        
        // 结果面板
        JPanel resultPanel = new JPanel(new BorderLayout(5, 5));
        resultPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(PRIMARY_COLOR),
                "查询结果",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                LABEL_FONT,
                PRIMARY_COLOR));
        
        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JPanel resultInfoPanel = new JPanel(new BorderLayout());
        resultInfoPanel.add(resultCountLabel, BorderLayout.WEST);
        
        resultPanel.add(resultInfoPanel, BorderLayout.NORTH);
        resultPanel.add(scrollPane, BorderLayout.CENTER);
        
        // 底部按钮面板
        JPanel bottomButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton selectButton = createStyledButton("选择", BUTTON_COLOR);
        JButton cancelButton = createStyledButton("取消", BUTTON_COLOR);
        
        bottomButtonPanel.add(selectButton);
        bottomButtonPanel.add(cancelButton);
        
        // 顶部面板（标题+查询条件+按钮）
        JPanel topPanel = new JPanel(new BorderLayout(10, 10));
        topPanel.setBorder(new EmptyBorder(10, 10, 5, 10));
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(criteriaPanel, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加到主面板
        add(topPanel, BorderLayout.NORTH);
        add(resultPanel, BorderLayout.CENTER);
        add(bottomButtonPanel, BorderLayout.SOUTH);
        
        // 设置事件监听器
        searchButton.addActionListener(e -> performSearch());
        resetButton.addActionListener(e -> resetFields());
        selectButton.addActionListener(e -> selectRecord());
        cancelButton.addActionListener(e -> dispose());
        
        // 设置回车键触发搜索
        getRootPane().setDefaultButton(searchButton);
    }
    
    /**
     * 创建带有指定字体的标签
     * @param text 标签文本
     * @return 标签对象
     */
    private JLabel createLabelWithFont(String text) {
        JLabel label = new JLabel(text);
        label.setFont(LABEL_FONT);
        return label;
    }
    
    /**
     * 创建统一风格的按钮
     * @param text 按钮文本
     * @param bgColor 背景颜色
     * @return 按钮对象
     */
    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(BUTTON_FONT);
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        return button;
    }
    
    /**
     * 设置事件监听器
     */
    private void setupListeners() {
        // 双击选择记录
        resultTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    selectRecord();
                }
            }
        });
    }
    
    /**
     * 执行查询
     */
    private void performSearch() {
        try {
            // 创建查询条件对象
            QueryCriteria criteria = new QueryCriteria();
            
            // 设置订单ID
            if (!orderIdField.getText().trim().isEmpty()) {
                try {
                    criteria.setOrderId(Integer.parseInt(orderIdField.getText().trim()));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "订单ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            // 设置订单编号
            if (!orderNumberField.getText().trim().isEmpty()) {
                criteria.setOrderNumber(orderNumberField.getText().trim());
            }
            
            // 设置客户ID
            if (!customerIdField.getText().trim().isEmpty()) {
                try {
                    criteria.setCustomerId(Integer.parseInt(customerIdField.getText().trim()));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "客户ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            // 设置日期范围
            if (!startDateField.getText().trim().isEmpty()) {
                try {
                    LocalDate startDate = LocalDate.parse(startDateField.getText().trim(), DATE_FORMATTER);
                    criteria.setStartDate(startDate);
                } catch (DateTimeParseException e) {
                    JOptionPane.showMessageDialog(this, "开始日期格式不正确，请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            if (!endDateField.getText().trim().isEmpty()) {
                try {
                    LocalDate endDate = LocalDate.parse(endDateField.getText().trim(), DATE_FORMATTER);
                    criteria.setEndDate(endDate);
                } catch (DateTimeParseException e) {
                    JOptionPane.showMessageDialog(this, "结束日期格式不正确，请使用yyyy-MM-dd格式", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            // 设置订单状态
            if (orderStatusCombo.getSelectedIndex() > 0) {
                String statusDisplay = (String) orderStatusCombo.getSelectedItem();
                String statusCode = REVERSE_STATUS_MAP.get(statusDisplay);
                criteria.setOrderStatus(statusCode);
            }
            
            // 设置支付状态
            if (paymentStatusCombo.getSelectedIndex() > 0) {
                String statusDisplay = (String) paymentStatusCombo.getSelectedItem();
                String statusCode = REVERSE_PAYMENT_STATUS_MAP.get(statusDisplay);
                criteria.setPaymentStatus(statusCode);
            }
            
            // 设置金额范围
            if (!minAmountField.getText().trim().isEmpty()) {
                try {
                    criteria.setMinAmount(BigDecimal.valueOf(Double.parseDouble(minAmountField.getText().trim())));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "最小金额必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            if (!maxAmountField.getText().trim().isEmpty()) {
                try {
                    criteria.setMaxAmount(BigDecimal.valueOf(Double.parseDouble(maxAmountField.getText().trim())));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "最大金额必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            // 设置仓库ID
            if (!warehouseIdField.getText().trim().isEmpty()) {
                try {
                    criteria.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "仓库ID必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            
            // 设置关键字
            if (!keywordField.getText().trim().isEmpty()) {
                criteria.setKeyword(keywordField.getText().trim());
            }
            
            // 执行查询
            List<SalesOrders> resultList = SelectSalesOrder.advancedQuery(criteria);
            
            // 更新表格数据
            updateTableData(resultList);
            
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 更新表格数据
     * @param orderList 销售订单列表
     */
    private void updateTableData(List<SalesOrders> orderList) {
        // 清空表格
        tableModel.setRowCount(0);
        
        if (orderList != null && !orderList.isEmpty()) {
            for (SalesOrders order : orderList) {
                String orderDateStr = order.getOrderDate() != null ? 
                    order.getOrderDate().format(DATETIME_FORMATTER) : "";
                    
                tableModel.addRow(new Object[]{
                    order.getOrderId(),
                    order.getOrderNumber(),
                    order.getCustomerId(),
                    orderDateStr,
                    STATUS_MAP.get(order.getOrderStatus()),
                    PAYMENT_STATUS_MAP.get(order.getPaymentStatus()),
                    order.getTotalAmount()
                });
            }
            
            resultCountLabel.setText("查询结果: " + orderList.size() + " 条记录");
        } else {
            resultCountLabel.setText("查询结果: 0 条记录");
            JOptionPane.showMessageDialog(this, "未找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    /**
     * 重置所有字段
     */
    private void resetFields() {
        orderIdField.setText("");
        orderNumberField.setText("");
        customerIdField.setText("");
        startDateField.setText("");
        endDateField.setText("");
        orderStatusCombo.setSelectedIndex(0);
        paymentStatusCombo.setSelectedIndex(0);
        minAmountField.setText("");
        maxAmountField.setText("");
        warehouseIdField.setText("");
        keywordField.setText("");
        
        // 清空表格
        tableModel.setRowCount(0);
        resultCountLabel.setText("查询结果: 0 条记录");
    }
    
    /**
     * 选择记录并返回到主界面
     */
    private void selectRecord() {
        int selectedRow = resultTable.getSelectedRow();
        if (selectedRow >= 0) {
            // 获取选中的行数据
            int orderId = (int) tableModel.getValueAt(selectedRow, 0);
            
            // 获取选中的订单数据
            List<SalesOrders> orderList = SelectSalesOrder.selectById(orderId);
            
            if (!orderList.isEmpty()) {
                // 更新主界面表格
                if (mainTable != null) {
                    SalesMassage.updateTableData(mainTable, orderList);
                    
                    // 更新状态消息
                    com.xky.ui.main.MainView.updateStatusMessage("已选择订单ID: " + orderId);
                    
                    // 关闭对话框
                    dispose();
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择一条记录", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    /**
     * 主方法，用于测试
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(() -> {
            AdvancedQueryDialog dialog = new AdvancedQueryDialog(null, null);
            dialog.setVisible(true);
        });
    }
}